package com.cci.kangdao.utilTool;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class PublicTool {
	private static Logger log = Logger.getLogger(PublicTool.class);

	/**
	 *
	 * 获得系统时间.<br />
	 *
	 *
	 * @return
	 */
	public static String getNowTime() {
		java.util.Calendar c = java.util.Calendar.getInstance();
		java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String nowTime = f.format(c.getTime());
		return nowTime;
	}

	/**
	 * 得到当前时间的最大值、最小值
	 */
	public static String[] getMaxMinuteOfDay() {
		String[] date = new String[2];
		SimpleDateFormat simpleFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		date[0] = simpleFormate.format(calendar.getTime());// 最小值
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		date[1] = simpleFormate.format(calendar.getTime());// 最大值
		return date;
	}

	/**
	 * 得到当前小时的最大值、最小值
	 */
	public static String[] getMaxMinuteOfHour() {
		String[] date = new String[2];
		SimpleDateFormat simpleFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		date[0] = simpleFormate.format(calendar.getTime());// 最小值
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		date[1] = simpleFormate.format(calendar.getTime());// 最大值
		return date;
	}

	/**
	 * 得到当前分钟的最大值、最小值
	 */
	public static String[] getMaxMinuteOfMinute() {
		String[] date = new String[2];
		SimpleDateFormat simpleFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.SECOND, 0);
		date[0] = simpleFormate.format(calendar.getTime());// 最小值
		calendar.set(Calendar.SECOND, 59);
		date[1] = simpleFormate.format(calendar.getTime());// 最大值
		return date;
	}

	/**
	 * 获取当前日期是星期几<br>
	 *
	 * @param dt
	 * @return 当前日期是星期几
	 */
	public static String getWeekOfDate(Date dt) {
		String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);

		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;

		return weekDays[w];
	}

	/**
	 * 根据传入tigger的时间获取是否触发时间
	 *
	 * @param tigger
	 * @return
	 */
	public static boolean getWeekOfDate(String tigger) {
		Calendar cal = Calendar.getInstance();
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0)
			w = 0;
		tigger += "|";
		if (tigger.contains(w + "|")) {
			return true;
		}
		return false;
	}

	/**
	 * 根据传入tigger的时间获取是否触发时间
	 *
	 * @param tigger
	 * @return
	 */
	public static boolean getHourOfDay(String tigger) {
		SimpleDateFormat simpleFormate = new SimpleDateFormat("HH");
		String date1 = simpleFormate.format(Calendar.getInstance().getTime());
		if (tigger.contains(Integer.valueOf(date1) + "|")) {
			return true;
		}
		return false;
	}

	/**
	 * 根据活动的开始时间得到当前时间是活动的第几天
	 *
	 * @param beginTime
	 * @return
	 */
	public static int getActivityDay(String beginTime) {
		int day = 1;
		SimpleDateFormat simpleFormate = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date data1 = simpleFormate.parse(beginTime);
//			long l = Calendar.getInstance().getTime().getTime() - data1.getTime();
			long l = Calendar.getInstance().getTime().getTime() - data1.getTime();
			day = (int) (l / (24 * 60 * 60 * 1000));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return day;
	}

	/**
	 * 判断是否可以使用access-token
	 *
	 * @param begin
	 * @return true表示可以使用access-token，false表示不可以使用
	 */
	public static boolean isBegin(String begin) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.add(java.util.Calendar.MINUTE, -110);
		java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date now = c.getTime();
			Date beginDate = f.parse(begin);
			if (now.before(beginDate)) {
				return true;
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return false;
	}

	/**
	 *
	 * @Title: ThreeMD5
	 * @Description:三次MD5加密
	 * @param password
	 * @return
	 */
	public static String ThreeMD5(String password) {
		for (int i = 0; i < 3; i++) {
			password = compute(password);
		}
		return password;
	}

	/**
	 *
	 * MD5加密.<br />
	 *
	 *
	 * @param inStr
	 * @return
	 */
	public static String compute(String inStr) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		char[] charArray = inStr.toCharArray();
		byte[] byteArray = new byte[charArray.length];

		for (int i = 0; i < charArray.length; i++)
			byteArray[i] = (byte) charArray[i];

		byte[] md5Bytes = md5.digest(byteArray);

		StringBuffer hexValue = new StringBuffer();

		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16)
				hexValue.append("0");
			hexValue.append(Integer.toHexString(val));
		}

		return hexValue.toString();
	}
	/**
	 * 生产32随机数
	 * @return
	 */
	public static String getNonceStr(int temp) {
		String chars = "ABCDEFGHIJKLMNOPhijklmn123456opqrstuQRSTUVWXYZabcdefgvwxyz0789";
		int maxPos = chars.length();
		String noceStr = "";
		for (int i = 0; i < temp; i++) {
			noceStr += chars.charAt((int) (Math.random() * maxPos));
		}
		return noceStr;
	}
//	/**
//	 * 根据accoutid获取jsApiticket
//	 * @param accountid
//	 * @return
//	 */
//	public static String getJsApiticket(String posturl){
//		HttpRequestSms rq = new HttpRequestSms();
//		try {
//			String result = rq.doRequest(posturl, "get", null,
//					null);
//			return result.trim();
//		} catch (Exception e) {
//			log.error(e.getMessage(), e);
//		}
//		return null;
//	}
	/**
	 * 下载微信回复的图片消息中的图片
	 *
	 * @param urlString
	 * @param filename
	 * @param savePath
	 */
	public static boolean downloadPicture(String urlString, String filename, String savePath) {
		try {
			// 构造URL
			URL url = new URL(urlString);
			// 打开连接
			URLConnection con = url.openConnection();
			// 设置请求超时为5s
			con.setConnectTimeout(2 * 1000);
			// 输入流
			InputStream is = con.getInputStream();

			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			File sf = new File(savePath);
			if (!sf.exists()) {
				sf.mkdirs();
			}
			OutputStream os = new FileOutputStream(sf.getPath() + "/" + filename);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			return false;
		}
		return true;
	}

	/**
	 * 删除单个文件或清空文件夹
	 */
	public static void deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists()) {
			if (file.isFile()) {
				if (file.delete()) {
					// System.out.println("删除" + fileName + "成功！");
				} else {
					// System.out.println("删除" + fileName + "失败！");
				}
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
					deleteFile(files[i].getPath()); // 把每个文件 用这个方法进行迭代
				}
			}

		} else {
			// System.out.println(fileName + "不存在！");
		}
	}

	/**
	 *
	 * 获得HTTP请求的IP地址.<br />
	 *
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip != null) {
			String[] ipArray = ip.split(",");
			if (ipArray != null && ipArray.length > 1) {
				ip = ipArray[0];
			}
		}
		return ip;
	}

	/**
	 * 产生随机验证码
	 *
	 * @return
	 */
	public static String getFourRandom() {
		Random random = new Random();
		String fourRandom = random.nextInt(1000000) + "";
		int randLength = fourRandom.length();
		if (randLength < 6) {
			for (int i = 1; i <= 6 - randLength; i++) {
				fourRandom = "0" + fourRandom;
			}
		}
		return fourRandom;
	}

	/**
	 * 产生订单号
	 *
	 * @return
	 */
	public static String getOrderIdByUUId() {
		int machineId = 0;// 最大支持1-9个集群机器部署
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if (hashCodeV < 0) {// 有可能是负数
			hashCodeV = -hashCodeV;
		}
		// 0 代表前面补充0
		// 4 代表长度为4
		// d 代表参数为正数型
		java.util.Calendar c = java.util.Calendar.getInstance();
		java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyMMdd");
		String nowTime = f.format(c.getTime());

		return nowTime + String.format("%010d", hashCodeV);
		// return nowTime+ machineId + String.format("%010d", hashCodeV);
	}

	/**
	 * 产生随机验证码
	 *
	 * @return
	 */
	public static String getNewRandom() {
		Random random = new Random();
		int fourRandom = random.nextInt(100000000);
		return String.format("%08d", fourRandom);
	}

	/**
	 *
	 * @Title: getpagenum
	 * @Description:计算总页数。
	 * @param count
	 * @param pagesize
	 * @return
	 */
	public static int getpagenum(int count, int pagesize) {
		int pagenum = 0;
		pagenum = count % pagesize == 0 ? count / pagesize : (int) Math
				.floor(count / pagesize) + 1;
		return pagenum;
	}

	/**
	 *
	 * @Title: getpage
	 * @Description: 验证page
	 * @param pageAllnum
	 * @param page
	 * @return
	 */
	public static int getpage(int pageAllnum, int page) {
		int num = 0;
		if (page > pageAllnum) {
			num = pageAllnum;
		} else if (page <= 0) {
			num = 1;
		} else {
			num = page;
		}
		return num;
	}

	/**
	 *
	 * @Title: getStart
	 * @Description:计算分页开始记录数
	 * @param page
	 * @param pagesize
	 * @return
	 */
	public static int getStart(int page, int pagesize) {
		int start = pagesize * (page - 1);
		return start;
	}

	/**
	 * 输入001返回002，输入001_001返回001_002
	 *
	 * @param layer
	 * @return
	 */
	public static String getLayer(String layer) {
		String inter = layer.substring(layer.lastIndexOf("_") + 1);
		inter = String.valueOf(Integer.valueOf(inter) + 1);
		if (inter.length() == 1) {
			inter = "00" + inter;
		} else if (inter.length() == 2) {
			inter = "0" + inter;
		}

		if (layer.lastIndexOf("_") < 0) {
			return inter;
		}
		inter = layer.substring(0, layer.lastIndexOf("_") + 1) + inter;
		return inter;
	}

	/**
	 * 将当前时间转换为美国时间
	 * @param dateTime
	 * @return
	 */
	public static String dateTimeChangeUs(String dateTime){

		SimpleDateFormat foo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{
	        // 1、取得本地时间：
	        java.util.Calendar cal = java.util.Calendar.getInstance();
	        cal.setTimeInMillis(foo.parse(dateTime).getTime());
//	        // 2、取得时间偏移量：
//	        int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
//	        // 3、取得夏令时差：
//	        int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
//	        // 4、从本地时间里扣除这些差量，即可以取得UTC时间：
//	        cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));

	        //因为服务器在美国，所以不能根据地区计算
	        cal.add(java.util.Calendar.HOUR_OF_DAY, -8);
	        return foo.format(new Date(cal.getTimeInMillis()))+".0000000 +00:00";
		}catch (Exception e) {
			e.printStackTrace();
		}
		return dateTime;
	}

	/**
	 * 将美国时间转换为当前时间
	 * @param dateTime
	 * @return
	 */
	public static String dateTimeChangeChina(String dateTime){

		SimpleDateFormat foo = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{
	        // 1、取得本地时间：
	        java.util.Calendar cal = java.util.Calendar.getInstance();
	        cal.setTimeInMillis(foo.parse(dateTime).getTime());
//	        // 2、取得时间偏移量：
//	        int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
//	        // 3、取得夏令时差：
//	        int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
//	        // 4、从本地时间里扣除这些差量，即可以取得UTC时间：
//	        cal.add(java.util.Calendar.MILLISECOND, +(zoneOffset + dstOffset));

			//因为服务器在美国，所以不能根据地区计算
			cal.add(java.util.Calendar.HOUR_OF_DAY, +8);
			return foo.format(new Date(cal.getTimeInMillis()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return dateTime;
	}

	public static String hex(byte[] a) {
		StringBuilder sb = new StringBuilder(a.length * 2);
		for (byte b : a) {
			sb.append(String.format("%02x", b));
		}
		return sb.toString();
	}

	public static String md5(byte[] bytes) {

		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		digest.update(bytes);
		return hex(digest.digest());
	}

	public static void main(String[] args) {

	}

}
